var SecurityUtil = require('../lib/utils/SecurityUtil');
var connection = require('../lib/utils/DbconnectUtil');
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var variables = require('../config/variables');
var config = require("../config/setting");

var express = require('express');
var router = express.Router();
//@Deprecated
router.get('/', function (req, res, next) {

    var email = req.query.email;
    var encodedData = req.query.authToken;

    if (!email || !encodedData) {
        resData.result = false;
        resData.message = "无效的密码重置请求";
        res.send(resData);
        return;
    }

    var decodedData = SecurityUtil.decipher(encodedData, email);

    var resData = {};

    var data = decodedData.split("#");
    if (!data || data.length != 3) {
        resData.result = false;
        resData.message = "无效的密码重置请求";
        res.send(resData);
        return;
    }
    if (data[1] != email) {
        resData.result = false;
        resData.message = "无效的密码重置请求";
        res.send(resData);
        return;
    }
    //12小时则无效
    if (new Date().getTime() - parseInt(data[2]) > 43200000) {
        resData.result = false;
        resData.message = "重置请求已过期";
        res.send(resData);
        return;
    }
    resData.result = true;
    resData.message = "请求成功";
    resData.data = encodedData;
    res.send(resData);
});

router.post('/email/', function (req, res, next) {

    req.body.email = req.body.email ;

    var resData = {};

    if(!req.body.email){
        resData.result = false;
        resData.message = "请求参数不合法";
        res.send(resData);
        return;
    }
    connection().query('select * from t_user where email = ? ', [req.body.email], function (err, result) {
        if (err) {
            resData.result = false;
            resData.message = "无法访问数据服务器";
            res.send(resData);
            return;
        }

        if (result && result[0]) {

            var email = result[0].email;
            var now = new Date().getTime();
            var salt = result[0].salt;
            var requestData = salt + "#" + email + "#" + now.toString();
            var encodedData = SecurityUtil.cipher(requestData, email);

            var currentEnv = global.CURRENT_ENV ? global.CURRENT_ENV : 'production';
            var host = config.domainHost[currentEnv].url;

            var url = host+"/#/newPassword?email=" + email + "&authToken=" + encodedData;
            var html = "<a href='" + url + "'>"+url+"</a>";

            var transport = nodemailer.createTransport(smtpTransport(variables.SMTPConfig));

            var mailOptions = {
                from: '顺义慈善网站 <'+variables.SMTPConfig.auth.user+'>',
                to: email,
                subject:"重置密码",
                html:html
            };

            transport.sendMail(mailOptions, function(error, info){
                if(error){
                    console.log('send Message Error: ' +JSON.stringify(error));
                    resData.result = false;
                    resData.message = "发送邮件失败,休息一会儿再试";
                    res.send(resData);
                }else{
                    resData.result = true;
                    resData.data = info.response;
                    resData.message = "发送成功";
                    res.send(resData);
                }
            });
            return;
        }
        else {
            resData.result = false;
            resData.message = "当前账号未注册";
            res.send(resData);
            return;
        }

    });

});


router.post('/', function (req, res, next) {
    var email = req.body.email;
    var encodedData = req.body.authToken;
    var newPassword = req.body.password;

    var resData = {};
    if(!email || !encodedData || !newPassword){
        resData.result = false;
        resData.message = "参数缺失";
        res.send(resData);
        return;
    }

    var decodedData = SecurityUtil.decipher(encodedData, email);

    var data = decodedData.split("#");
    if (!data || data.length != 3) {
        resData.result = false;
        resData.message = "无效的密码重置请求";
        res.send(resData);
        return;
    }
    if (data[1] != email) {
        resData.result = false;
        resData.message = "无效的密码重置请求";
        res.send(resData);
        return;
    }
    //12小时则无效
    if (new Date().getTime() - parseInt(data[2]) > 43200000) {
        resData.result = false;
        resData.message = "重置请求已过期";
        res.send(resData);
        return;
    }

    var encodedPassword = SecurityUtil.genPasswordCipherText(newPassword, data[0]);

    connection().query('update t_user set password = ? where email = ? and salt = ?', [encodedPassword,data[1],data[0]], function (err, result) {
        if (err) {
            resData.result = false;
            resData.message = "无法访问数据服务器";
            res.send(resData);
            return;
        }
        else{
            resData.result = true;
            resData.data = result;
            resData.message = "重置密码成功";
            res.send(resData);
        }

    });

});


module.exports = router;
